<template>
  <div class="search-box">
    <!-- 搜索头部导航 -->
    <form class="searchForm" action="/">
      <van-search
        v-model="searchKey"
        show-action
        clearable
        background="#3296fa"
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="$router.go(-1)"
        @focus="resultsFlag = false"
      />
    </form>
    <!-- 搜索结果 -->
    <search-results :searchData="searchKey" v-if="resultsFlag"></search-results>
      <!-- 搜索建议 -->
    <search-steer @search-keys="onSearch" :serachKeys="searchKey" v-else-if="searchKey"></search-steer>
    <!-- 搜索历史 -->
    <search-history @searchLink="onSearch" @clearAll="historyData = []" :searchHistory="historyData" v-else></search-history>

  </div>
</template>

<script>
import SearchHistory from './components/search-history'
import SearchSteer from './components/search-steer.vue'
import SearchResults from './components/search-results.vue'
import { getItem, setItem } from '@/utils/storage'
const historyKeys = 'HISTORYKEYS-DATA'
export default {
  name: 'serach',
  data () {
    return {
      searchKey: '',
      resultsFlag: false,
      historyData: getItem(historyKeys) || []
    }
  },

  created () {

  },

  watch: {
    historyData () {
      setItem(historyKeys, this.historyData)
    }
  },

  components: {
    SearchHistory,
    SearchResults,
    SearchSteer
  },

  methods: {
    // 搜索确定
    onSearch (val) {
      val = val.trim()
      if (val.length <= 0) return this.$toast('请添加必要的搜索关键字')
      const index = this.historyData.indexOf(val)
      if (index !== -1) {
        this.historyData.splice(index, 1)
      }
      this.historyData.unshift(val)
      this.searchKey = val
      this.resultsFlag = true
    }
  }
}
</script>

<style scoped lang='less'>
.van-search__action {
  color: #f6f6f6;
}
.searchForm {
  position: sticky;
  top: 0;
//   width: 100%;
  z-index: 999;
  }
</style>
